// pages/learn/learn.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    problems: [],  // 存放算术题及其答案
    userAnswers: {},  // 存储用户输入的答案
    ex_id: Number(0),
    my_answer: 0,
    star_png: ["../../images/notstar.png","../../images/isstar.png"],
    isstar: [],
    donecondition: 0,
    blank: "",
    result: [],  // 存储答题结果
    isCorrect: false,
    startTime: 0,       // 记录计时开始的时间戳
    elapsedTime: 0,     // 记录已用时间
    elapsedTimeFormatted: '0.0',  // 新增，用于存储格式化后的时间
    timer: null         // 计时器
  },

  stopTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      });
    }
    const endTime = Date.now();
    const elapsedTime = endTime - this.data.startTime;
    this.setData({
      elapsedTime: elapsedTime,
      elapsedTimeFormatted: (elapsedTime / 1000).toFixed(1)
    });
    console.log('本次用时：' + this.data.elapsedTimeFormatted + '秒');

    // 每次计时器停止时，调用 updateUserStats()
    this.updateUserStats();
  },

  // 更新用户的总答题时间和总做题次数
  updateUserStats() {
    const elapsedTimeInSeconds = Math.round(this.data.elapsedTime / 1000); // 将毫秒转换为秒
    const totalExercises = this.data.ex_id + 1; // 已完成的题目数量
  
    // 更新全局变量
    app.globalData.userInfo.totaltime += elapsedTimeInSeconds;
    app.globalData.userInfo.totalexe += totalExercises;
  
    // 输出调试信息
    console.log('开始更新用户统计数据:');
    console.log('本次用时（秒）:', elapsedTimeInSeconds);
    console.log('本次做题数量:', totalExercises);
    console.log('更新后的总时间:', app.globalData.userInfo.totaltime);
    console.log('更新后的总做题次数:', app.globalData.userInfo.totalexe);
    console.log('用户 openid:', app.globalData.userInfo.openid);
  
    // 更新数据库中的用户信息
    const db = wx.cloud.database();
    db.collection('user').where({
      _openid: app.globalData.userInfo.openid
    }).update({
      data: {
        totaltime: app.globalData.userInfo.totaltime,
        totalexe: app.globalData.userInfo.totalexe
      },
      success: res => {
        if (res.stats && res.stats.updated > 0) {
          console.log('用户总时间和总做题次数更新成功', res);
        } else {
          console.error('未找到对应的用户文档，无法更新');
          wx.showToast({
            title: '更新失败，未找到用户文档',
            icon: 'none'
          });
        }
      },
      fail: err => {
        console.error('用户总时间和总做题次数更新失败', err);
        wx.showToast({
          title: '更新失败，请稍后再试',
          icon: 'none'
        });
      }
    });
  },

  // 将题目添加到数据库的 star 集合
  addToDatabase(item) {
    const db = wx.cloud.database();
    const { openid } = app.globalData.userInfo; // 确保您已经有了用户的 openid
    // 检查数据库中是否已经存在这个问题，避免重复添加
    db.collection('star').where({
      openid: openid,
      content: item
    }).get({
      success: function(res) {
        if (res.data.length === 0) {
          db.collection('star').add({
            data: {
              openid: openid,
              content: item
            },
            success: res => {
              console.log('添加到收藏成功', res);
            },
            fail: err => {
              console.error('添加到收藏失败', err);
            }
          });
        }
      }
    });
  },

  // 提交答案
  commit() {
    // 更改提交状态
    this.setData({
      donecondition: 1
    });

    // 检查答案
    this.checkAnswers();

    if (this.data.isCorrect === true) {
      // 答案正确
      wx.showToast({
        title: '正确',
        icon: 'success',
        duration: 1000
      });
    } else {
      // 答案错误
      wx.showToast({
        title: '错误',
        icon: 'error',
        duration: 1000
      });
      // 将错误的题目添加到收藏
      let tmp = app.globalData.starbook;
      let ques = this.data.problems[this.data.ex_id].question;
      if (!tmp.includes(ques)) {
        tmp.push(ques);
        this.addToDatabase(ques); // 同步到数据库
      }
      app.globalData.starbook = tmp;
    }

    // 判断是否是最后一题
    if (this.data.ex_id >= this.data.problems.length - 1) {
      // 用户已完成所有题目，停止计时
      this.stopTimer();

      // 显示完成提示
      wx.showModal({
        title: '恭喜',
        content: '您已完成所有题目！总用时：' + this.data.elapsedTimeFormatted + '秒',
        showCancel: false,
        confirmText: '返回首页',
        success: (res) => {
          if (res.confirm) {
            // 返回首页或执行其他操作
            wx.switchTab({
              url: '/pages/home/home' // 替换为首页实际路径
            });
          }
        }
      });
    } else {
      // 不是最后一题，进入下一题
      this.next_ex();
    }
  },

  next_ex() {
    if (this.data.ex_id >= this.data.problems.length - 1) {
      wx.showToast({
        title: '已经是最后一题了',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    this.setData({
      ex_id: this.data.ex_id + 1,
      donecondition: 0,
      blank: ""
    });
  },

  last_ex(){
    this.setData({
      ex_id: this.data.ex_id - 1,
      blank: ""
    })
  },

  // 输入函数
  inputhandler(e){
    var a = e.detail.value
    this.setData({
      my_answer: a
    })
    // console.log(this.data.my_answer)
  },

  // 判断是否收藏
  my_star(){
    if( this.data.isstar[this.data.ex_id] ){
      this.setData({
        ['isstar['+this.data.ex_id+']'] : 0
      })
    }
    else{
      let ques = this.data.problems[this.data.ex_id].question;
      if( !app.globalData.starbook.includes(ques) )
        app.globalData.starbook.push(ques);
        this.addToDatabase(ques); // 添加到数据库
      this.setData({
        ['isstar[' + this.data.ex_id + ']']: 1
      })
    }
  },

  // 计算表达式的结果，支持括号和运算优先级
  calculateResult(tokens) {
    const ops = {
      '+': (a, b) => a + b,
      '-': (a, b) => a - b,
      '*': (a, b) => a * b,
      '÷': (a, b) => {
        if (b === 0 || a % b !== 0) throw new Error('Invalid division');
        return Math.floor(a / b);
      },
    };

    const precedence = {
      '+': 1,
      '-': 1,
      '*': 2,
      '÷': 2,
    };

    const values = [];
    const operators = [];

    function applyOperator() {
      const operator = operators.pop();
      const b = values.pop();
      const a = values.pop();
      if (operator === '÷' && (b === 0 || a % b !== 0)) {
        throw new Error('Invalid division');
      }
      const result = ops[operator](a, b);
      values.push(result);
    }

    for (let i = 0; i < tokens.length; i++) {
      const token = tokens[i];
      if (typeof token === 'number') {
        values.push(token);
      } else if (token === '(') {
        operators.push(token);
      } else if (token === ')') {
        while (operators.length && operators[operators.length - 1] !== '(') {
          applyOperator();
        }
        operators.pop(); // 移除 '('
      } else if (['+', '-', '*', '÷'].includes(token)) {
        while (
          operators.length &&
          precedence[operators[operators.length - 1]] >= precedence[token] &&
          operators[operators.length - 1] !== '('
        ) {
          applyOperator();
        }
        operators.push(token);
      }
    }

    while (operators.length) {
      applyOperator();
    }

    if (values.length !== 1) {
      throw new Error('Invalid expression');
    }

    return values.pop();
  },

  // 生成包含括号的单个算术题
  generateProblemWithParentheses(numOperands, maxNumber, operations) {
    let operands = [];
    let operators = [];

    // 生成操作数
    for (let i = 0; i < numOperands; i++) {
      operands.push(Math.ceil(Math.random() * maxNumber));
    }

    // 生成操作符
    for (let i = 0; i < numOperands - 1; i++) {
      operators.push(operations[Math.floor(Math.random() * operations.length)]);
    }

    // 构建表达式的 tokens 数组
    let tokens = [];
    for (let i = 0; i < operands.length; i++) {
      tokens.push(operands[i]);
      if (i < operators.length) {
        tokens.push(operators[i]);
      }
    }

    // 随机决定是否添加括号
    let useParentheses = Math.random() < 0.7; // 70% 的概率添加括号

    if (useParentheses && numOperands >= 3) {
      // 有效的开始索引为偶数（操作数的位置）
      let possibleStartIndices = [];
      for (let i = 0; i < tokens.length - 2; i += 2) {
        possibleStartIndices.push(i);
      }

      let startIdx = possibleStartIndices[Math.floor(Math.random() * possibleStartIndices.length)];

      // 有效的结束索引为大于开始索引的偶数
      let possibleEndIndices = [];
      for (let i = startIdx + 2; i < tokens.length; i += 2) {
        possibleEndIndices.push(i);
      }

      let endIdx = possibleEndIndices[Math.floor(Math.random() * possibleEndIndices.length)];

      // 在 tokens 中插入括号
      tokens.splice(endIdx + 1, 0, ')');
      tokens.splice(startIdx, 0, '(');
    }

    // 计算答案
    let answer;
    try {
      answer = this.calculateResult(tokens);
    } catch {
      return null; // 无效题目，返回 null，生成下一个
    }

    if (answer === null || answer < 0 || answer > 500) {
      return null; // 答案不符合要求，返回 null，生成下一个
    }

    // 生成题目字符串
    let question = tokens
      .map((token) => (typeof token === 'number' ? token : token))
      .join(' ');

    return { question, answer };
  },

  generateProblems(grade) {
    let problems = [];
    let totalProblems = app.globalData.plan;
    let numOperands, maxNumber, operations;
    // 生成收藏数组
    let array = new Array(totalProblems).fill(0);
    this.setData({
      isstar: array
    });

    switch (grade) {
      case 1:
        numOperands = 2;
        maxNumber = 10;
        operations = ['+', '-'];
        break;
      case 2:
        numOperands = 2;
        maxNumber = 100;
        operations = ['+', '-'];
        break;
      default:
        numOperands = 3; // 可以根据需要调整操作数数量
        maxNumber = 100;
        operations = ['+', '-', '*', '÷'];
    }

    while (problems.length < totalProblems) {
      let problem = this.generateProblemWithParentheses(numOperands, maxNumber, operations);
      if (problem) {
        problems.push({ question: problem.question, answer: problem.answer, id: problems.length });
      }
    }
    this.setData({ problems });
  },

  checkAnswers() {
    this.setData({
      isCorrect: Number(this.data.problems[this.data.ex_id].answer) === Number(this.data.my_answer)
    })
  },

  onLoad(options) {
    let grade = app.globalData.grade;
    this.generateProblems(grade);
  },

  onHide() {
    // 停止计时器
    this.stopTimer();
  },

  onUnload() {
    // 停止计时器
    this.stopTimer();
  },

  onShow() {
    console.log("Displaying problems:", this.data.problems);

    // 重新生成题目
    let grade = app.globalData.grade;
    this.generateProblems(grade);

    // 开始计时
    this.setData({
      ex_id: 0, // 重置为第一题
      donecondition: 0, // 重置答题状态
      blank: "", // 清空用户输入
      startTime: Date.now(),
      elapsedTime: 0
    });

    // 启动定时器，每 100 毫秒更新一次已用时间
    this.data.timer = setInterval(() => {
      const elapsedTime = Date.now() - this.data.startTime;
      this.setData({
        elapsedTime: elapsedTime,
        elapsedTimeFormatted: (elapsedTime / 1000).toFixed(1)
      });
    }, 100);
  },
});